package com.sys;

import java.io.File;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;

import android.content.Context;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Log;

public class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {

	private static final String TAG = "MyUncaughtExceptionHandler";
	private static UncaughtExceptionHandler exceptionHandler;
	private static Context mContext;

	private MyUncaughtExceptionHandler() {
		exceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
	}

	private static MyUncaughtExceptionHandler handler = new MyUncaughtExceptionHandler();

	public static MyUncaughtExceptionHandler getExceptionHandler(Context context) {
		mContext = context;
		return handler;
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		Log.d(TAG, "get UncaughtException!!!");
		ex.printStackTrace();

		PrintStream ps;
		String dir = Environment.getExternalStorageDirectory() + "/mgq_err.txt";
		File file = new File(dir);

		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			ps = new PrintStream(file);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private String getPhoneInfo() {
		StackTraceElement cut_off_rule1 = new StackTraceElement(
				"---------------------", "----------------", "---------------",
				0);

		TelephonyManager mTm = (TelephonyManager) mContext
				.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = mTm.getDeviceId();
		if (imei == null || "".equals(imei))
			imei = "null";
		StackTraceElement imei_info = new StackTraceElement("\nimei_info: ",
				imei, "imei_info", 2);

		String imsi = mTm.getSubscriberId();
		if (imsi == null || "".equals(imsi))
			imsi = "null";
		StackTraceElement imsi_info = new StackTraceElement("\nimsi_info: ",
				imsi, "imsi_info", 3);

		String mtype = android.os.Build.MODEL; // ????????????
		if (mtype == null || "".equals(mtype))
			mtype = "null";
		StackTraceElement mtype_info = new StackTraceElement("\nmtype_info: ",
				mtype, "mtype_info", 4);

		String number = mTm.getLine1Number(); // ?????????????????????????????????????????????
		if (number == null || "".equals(number))
			number = "null";
		StackTraceElement numer_info = new StackTraceElement("\nnumber_info: ",
				number, "numer_info", 5);

		StackTraceElement cut_off_rule2 = new StackTraceElement(
				"---------------------", "----------------", "---------------",
				6);
		StringBuffer sbuffer = new StringBuffer();
		sbuffer.append(cut_off_rule1);
		sbuffer.append(imei_info);
		sbuffer.append(imsi_info);
		sbuffer.append(mtype_info);
		sbuffer.append(numer_info);
		sbuffer.append(cut_off_rule2);
		return sbuffer.toString();
	}
}